import { defineStore } from 'pinia'
import { apiAccount, apiNav } from '@renderer/api/bilibili'
import { apiLoginExit } from '@renderer/api/bilibili'
import router from '@renderer/router'

interface State {
  userName: string
  userAvatar: string
  userSign: string
  isLogin: boolean
  userMid: number
}

const { cookies } = window.api

export const useUserStore = defineStore('user', {
  state: (): State => ({
    userName: '',
    userAvatar: '',
    userSign: '',
    isLogin: false,
    userMid: 0
  }),
  getters: {},
  actions: {
    async getUserInfo() {
      try {
        const navData = await apiNav()
        const { uname, face, mid, wbi_img } = navData.data
        this.userName = uname
        this.userAvatar = face
        this.userMid = mid

        const accountData = await apiAccount()
        const { sign } = accountData.data
        this.userSign = sign

        this.isLogin = true

        // 为了wbi.js鉴权使用
        sessionStorage.setItem('img_url', wbi_img.img_url)
        sessionStorage.setItem('sub_url', wbi_img.sub_url)
      } catch (e) {
        if (e instanceof Error) {
          console.error(e.message)
        } else {
          console.error(e)
        }
      }
    },
    setIsLogin(val: boolean) {
      this.isLogin = val
    },
    async logout() {
      const biliCSRF = await cookies('https://bilibili.com').getValue('bili_jct')
      const { code } = await apiLoginExit({ biliCSRF })
      if (code === 0) {
        router.push({ name: 'home' })
        this.clearUserInfo()
      }
    },
    clearUserInfo() {
      this.userName = ''
      this.userAvatar = ''
      this.userSign = ''
      this.isLogin = false
      this.userMid = 0
    }
  }
})
